package com.wanxi.education.service.security;

import com.wanxi.education.model.vo.user.PermissionVO;
import com.wanxi.education.model.vo.user.RoleVO;
import com.wanxi.education.model.vo.user.UserVO;
import com.wanxi.education.service.LoginService;
import com.wanxi.education.service.PermissionService;
import com.wanxi.education.service.RoleService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.HashSet;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @Author: Kang
 * @Date: 2021/9/24 15:36
 * @Description: 用户权限管理
 * @Version: 1.0
 */
@Service
@Slf4j
public class UserService implements UserDetailsService {

    @Autowired
    private LoginService loginService;

    @Autowired
    private RoleService roleService;

    @Autowired
    private PermissionService permissionService;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Override
    public UserDetails loadUserByUsername(String phone) throws UsernameNotFoundException {
        log.info("进入到loadUserByUsername"+phone);
//        UserVO userVO = findByPhone(phone);
        UserVO user = loginService.findByPhone(phone);
        if (user == null) {
            throw new UsernameNotFoundException("账户不存在");
        }

        /**
         * 根据用户ID获取授权的权限
         * 1、通过用户ID查询用户所有角色Id
         * 2、通过用户所属角色Id查出角色所属权限Id及所对应的权限基本信息
         */
        Set<RoleVO> roleVOSet = roleService.findByUserId(user.getId());
        //        判断是否具有角色
        if (roleVOSet.size() == 0) {
            //        存储权限集合
            Set<GrantedAuthority> authorities = new HashSet<>();
            //        Id，昵称，手机号码，密码，权限
            UserVO userVO = new UserVO(user.getId(),user.getUsername(),user.getPhone(),passwordEncoder.encode(user.getPassword()),authorities);
            return userVO;
        }
        Set<Long> roleIds = roleVOSet.stream().map(RoleVO::getId).collect(Collectors.toSet());
//        2、通过用户所属角色Id查出角色所属权限Id及所对应的权限基本信息
        Set<PermissionVO> permissionVOSet = permissionService.findByRoleId(roleIds);
//        提取出权限路径
        Set<String> authoritie = permissionVOSet.stream().map(PermissionVO::getUri).collect(Collectors.toSet());
        //        存储权限集合
        Set<GrantedAuthority> authorities = new HashSet<>();
        for (String s : authoritie) {
            authorities.add(new SimpleGrantedAuthority(s));
        }
        //        Id，昵称，手机号码，密码，权限
        UserVO userVO = new UserVO(user.getId(),user.getUsername(),user.getPhone(),passwordEncoder.encode(user.getPassword()),authorities);
        return userVO;
    }

    /**
     * 模拟数据库交互账号
     * @param phone
     * @return
     */
    public UserVO findByPhone(String phone) {
        if (phone.equals("158299123")) {
            UserVO userVO = UserVO.builder()
                    .id(1L)
                    .username("张三")
                    .phone("158299123")
                    .password("123456").build();
            return userVO;
        }
        return null;
    }

}
